import { useRef, useState, useEffect } from 'react';
import { Modal, message } from 'antd';
import { ProForm, ProFormSelect } from '@ant-design/pro-components';
import { getListExcludeOwner, saveManagerList, queryKnowledgeDetail } from '@/services/knowledge';

import type { ProFormInstance } from '@ant-design/pro-components';

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 18 },
};

interface Props {
  managerVisible: boolean;
  managerId: string;
  managerTitle: string;
  closeModel: () => void;
}

const ManagerModel: React.FC<Props> = (props) => {
  const { managerVisible, managerId, managerTitle, closeModel } = props;
  const formRef = useRef<ProFormInstance>();

  // 页面初始化查询
  const pageQueryComing = async () => {
    if (managerId) {
      const res = await queryKnowledgeDetail({ id: managerId });
      if (!res.code && res.data) {
        const selectedList: any = [];
        res.data.managerList?.map((item) => {
          selectedList.push(item.id);
        });
        formRef.current?.setFieldValue('roleId', selectedList);
      }
    }
  };

  useEffect(() => {
    if (managerVisible) {
      pageQueryComing();
    }
  }, [managerVisible]);

  /**
   * 获取用户列表
   */
  const getRoleList = async () => {
    const res = await getListExcludeOwner({
      id: managerId,
      type: '1', // 知识库可选择员工
    });
    if (!res.code && res.data) {
      return res.data.map((r): any => ({
        key: r?.id,
        label: r?.nickname,
        value: r?.id,
      }));
    }
    return [];
  };
  // 关闭
  const handleClose = () => {
    formRef.current?.resetFields();
    closeModel();
  };

  // 确定按钮
  const handleAdd = () => {
    formRef.current
      ?.validateFields()
      .then(async (values) => {
        const params = { knowledgeId: managerId, managerIdList: values.roleId };
        const res = await saveManagerList(params);
        const { code, data } = res || {};
        if (!code && data) {
          message.success('关联成功');
          handleClose();
        }
      })
      .catch(() => {});
  };

  return (
    <div>
      <Modal
        maskClosable={false}
        width={800}
        title={managerTitle}
        open={managerVisible}
        onOk={handleAdd}
        onCancel={handleClose}
      >
        <div style={{ minHeight: '160px' }}>
          <ProForm formRef={formRef} {...formItemLayout} layout="horizontal" submitter={false}>
            <ProFormSelect
              name="roleId"
              label="关联管理员"
              placeholder="请选择管理员"
              rules={[
                {
                  required: true,
                  message: '请选择管理员',
                },
              ]}
              request={getRoleList}
              mode="multiple"
              // showArrow={true}
              // tagRender={tagRender}
            />
          </ProForm>
        </div>
      </Modal>
    </div>
  );
};

export default ManagerModel;
